package cn.tohsaka.factory.dockercraft.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;

/**
 * Created by Xmsoft on 2016/8/4.
 */
public class session {
    File file;
    sessionbean bean;

    public session(String ssid) throws Exception {
        file = new File(System.getProperty("user.dir") + File.separator + "sessions" + File.separator + ssid);
        if (!file.exists()) {
            bean = new sessionbean();
            bean.ssid = ssid;
            bean.modify = System.currentTimeMillis();
            bean.data = new HashMap();
        } else {
            bean = new Gson().fromJson(new FileReader(file), new TypeToken<sessionbean>() {
            }.getType());
            if (bean.data == null) {
                bean.data = new HashMap();
            }
        }
    }

    public synchronized session set(String k, Object v) {
        bean.data.put(k, v);
        save();
        return this;
    }

    public Object get(String k) {
        return bean.data.get(k);
    }

    public synchronized session remove(String k) {
        bean.data.remove(k);
        save();
        return this;
    }

    private synchronized void save() {
        try {
            FileWriter fw = new FileWriter(file);
            fw.write(new Gson().toJson(bean));
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void clear() {
        String ssid = bean.ssid;
        bean = new sessionbean();
        bean.ssid = ssid;
        bean.modify = System.currentTimeMillis();
        bean.data = new HashMap();
        save();
        file.delete();
    }
}